import type { OriginalProduct, TransformedProduct,OriginalSku } from './types';
export function transformProductData(originalData: OriginalProduct): TransformedProduct {
  // 1. 基本信息转换
  const transformed: TransformedProduct = {
    id: originalData.id,
    name: originalData.name,
    description: originalData.description || '',
    category: originalData.category?.name || '',
    priceRange: getPriceRange(originalData.skus),
    defaultImage: getDefaultImage(originalData),
    images: originalData.images || [],
    specs: [],
    skus: []
  };

  // 2. 处理规格信息
  if (originalData.specs && originalData.specs.length > 0) {
    transformed.specs = originalData.specs.map(spec => ({
      name: spec.name,
      values: spec.values,
      images: spec.images || {}
    }));
  }

  // 3. 处理SKU信息
  if (originalData.skus && originalData.skus.length > 0) {
    transformed.skus = originalData.skus.map(sku => {
      const specsObj: Record<string, string> = {};
      if (sku.specs && sku.specs.length > 0) {
        sku.specs.forEach(spec => {
          specsObj[spec.spec_name] = spec.value;
        });
      }

      return {
        id: `sku_${sku.id}`,
        specs: specsObj,
        price: parseFloat(sku.price) || 0,
        originalPrice: parseFloat(sku.original_price || sku.price) || 0,
        stock: sku.stock || 0,
        image: sku.image || transformed.defaultImage,
        barcode: sku.sku_code || '',
        weight: '0.3kg' // 默认值，可根据实际数据调整
      };
    });
  }

  return transformed;
}

// 辅助函数：获取价格范围
function getPriceRange(skus: OriginalSku[]): [number, number] {
  if (!skus || skus.length === 0) return [0, 0];
  
  const prices = skus.map(sku => parseFloat(sku.price) || 0);
  return [Math.min(...prices), Math.max(...prices)];
}

// 辅助函数：获取默认图片
function getDefaultImage(product: OriginalProduct): string {
  if (product.images && product.images.length > 0) {
    return product.images[0];
  }
  
  // 尝试从SKU中获取图片
  if (product.skus && product.skus.length > 0) {
    const firstSkuWithImage = product.skus.find(sku => sku.image);
    if (firstSkuWithImage && firstSkuWithImage.image) {
      return firstSkuWithImage.image;
    }
  }
  
  return ''; // 默认空字符串
}